<?php

namespace App\Http\Controllers\Customer;


use App\Http\Controllers\Controller;
use App\Http\Requests\client\PreTakeRequest;
use App\Models\PreTakeModel;
use App\Models\PreGoodsModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class PreTake extends Controller
{
    use PreTakeRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $auth = $request->get('auth');
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $key_word = $request->input('key_word', '');
        $status = $request->input('status', '');
        $driver_id = $request->input('driver_id', '');
        $date_start = $request->input('date_start', '');
        $date_end = $request->input('date_end', '');


        $query = PreTakeModel::query()->with('goods')
            ->with(['province', 'city', 'district', 'car'])
            ->where('customer_id', $auth->id);

        if($driver_id){
            $query = $query->withWhereHas('driver', function ($query) use ($driver_id) {
                if ($driver_id) {
                    $query->where('id', $driver_id);
                }
            });
        }

        if($key_word){
            $query = $query->where('contact|company|mobile', 'like', '%'.$key_word.'%');
        }

        if($status){
            $query = $query->where('status', $status);
        }

        if($date_start && $date_end){
            $query = $query->whereBetween('pre_time', [$date_start, $date_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $count = 0;
            $volume = 0;
            $weight = 0;
            if($item->goods){
                $count = count($item->goods);
                foreach ($item->goods as $goods) {
                    $volume += $goods->volume;
                    $weight += $goods->weight;
                }
            }
            $res = [
                'id' => $item->id,
                'contact' => $item->contact,
                'company' => $item->company,
                'mobile' => $item->mobile,
                'pre_time' => $item->pre_time,
                'province' => $item->province->name ?? '',
                'city' => $item->city->name ?? '',
                'district' => $item->district->name ?? '',
                'address' => $item->address,
                'goods_count' => $count,
                'goods_volume' => $volume,
                'goods_weight' => $weight,
                'remarks' => $item->remarks,
                'status' => $item->status,
                'status_text' => PreTakeModel::STATUS_CUS[$item->status] ?? '',
                'driver' => $item->driver ? $item->driver->name : '',
                'take_time' => $item->take_time,
                'take_remarks' => $item->take_remarks
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }


    public function add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        DB::beginTransaction();
        try {

            $model = new PreTakeModel();
            $model->customer_id = $auth->id;
            $model->contact = $params['contact'];
            $model->company = $params['company'];
            $model->mobile = $params['mobile'];
            $model->pre_time = $params['pre_time'];
            $model->province_id = $params['province_id'];
            $model->city_id = $params['city_id'];
//            $model->district_id = $params['district_id'];
            $model->address = $params['address'];
            $model->remarks = $params['remarks'] ?? '';
            $model->save();

            if(!is_array($params['goods'])){
                return $this->error('货物信息数据格式不对');
            }

            $goods = [];
            foreach ($params['goods'] as $item) {
                $check_res = self::goods_check($item);
                if($check_res->faild){
                    return $this->error($check_res->err);
                }

                $volume = round($item['length'] * $item['width'] * $item['height'] / 1000000, 3);

                $goods[] = [
                    'pre_id' => $model->id,
                    'length' => $item['length'],
                    'width' => $item['width'],
                    'height' => $item['height'],
                    'weight' => $item['weight'],
                    'volume' => $volume,
                ];
            }

            $goods_model = new PreGoodsModel();
            $goods_model->insert($goods);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    public function detail(Request $request)
    {
        $id = $request->input('id', 0);

        $model = PreTakeModel::query()->with('goods')
            ->with(['province', 'city', 'district', 'car', 'driver'])->find($id);

        if (!$model) {
            return $this->error('数据不存在');
        }

        $return = [
            'pre_info' => [
                'contact' => $model->contact,
                'company' => $model->company,
                'mobile' => $model->mobile,
                'pre_time' => $model->pre_time,
                'province' => $model->province->name ?? '',
                'city' => $model->city->name ?? '',
                'district' => $model->district->name ?? '',
                'address' => $model->address,
                'remarks' => $model->remarks,
                'status_text' => PreTakeModel::STATUS[$model->status]
            ]
        ];

        $volume = 0;
        $weight = 0;
        $goods_list = [];
        if($model->goods){
            foreach ($model->goods as $goods){
                $volume += $goods->volume;
                $weight += $goods->weight;
                $goods_list[] = [
                    'length' => $goods->length,
                    'width' => $goods->width,
                    'height' => $goods->height,
                    'weight' => $goods->weight,
                    'volume' => $goods->volume,
                ];
            }
            $return['goods_info'] = [
                'volume' => $volume,
                'weight' => $weight,
                'goods_list' => $goods_list
            ];
        }else{
            $return['goods_info'] = [];
        }


        if($model->driver){
            $return['driver_info'] = [
                'name' => $model->driver->name ?? '',
                'mobile' => $model->driver->mobile ?? '',
                'car_number' => $model->car->car_number ?? '',
                'car_volume' => $model->car->volume ?? '',
                'car_weight' => $model->car->weight ?? '',
                'driver_location' => '',
            ];
        }else{
            $return['driver_info'] = [];
        }

        $return['log_info'] = [];
        if($model->arrange_time){
            $return['log_info'][] = [
                'time' => $model->arrange_time,
                'desc' => '安排取件'
            ];
        }

        if($model->driver_time){
            $return['log_info'][] = [
                'time' => $model->driver_time,
                'desc' => '司机取单'
            ];
        }

        if($model->fail_time){
            $return['log_info'][] = [
                'time' => $model->fail_time,
                'desc' => '取件失败' . ' ' . $model->take_remarks
            ];
        }

        if($model->take_time){
            $return['log_info'][] = [
                'time' => $model->take_time,
                'desc' => '取件时间'
            ];
        }

        if($model->warehouse_time){
            $return['log_info'][] = [
                'time' => $model->warehouse_time,
                'desc' => '送达仓库'
            ];
        }

        return $this->success($return);
    }


    public function cancel(Request $request, $id)
    {
        $model = PreTakeModel::find($id);
        if(!$model) {
            return $this->error('记录不存在');
        }
        if($model->status != 1){
            return $this->error('已安排司机取件');
        }
        $model->delete();
        return $this->success();

    }


}
